//
//  TDOrderListC.m
//  TBRentClient
//
//  Created by tonbright on 2018/6/14.
//  Copyright © 2018年 tonbright. All rights reserved.
//

static NSString *showrows = @"4";
#import "TDOrderListC.h"
#import "TDOrderListHeadView.h"
#import "TDOrderListCell.h"
#import "UIView+ZLExtension.h"
#import "TDSearchCarController.h"
#import "TDOrderDetailC.h"
#import "NetWorkRequest.h"
#import "TDOrderListModel.h"
#import "BaseNavigationController.h"
@interface TDOrderListC ()
@property(nonatomic,assign)CGFloat historyOffY;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)TDOrderListHeadView *orderListHeadView;
@property (nonatomic,strong)TDOrderListHeadView *orderListFootView;
@property (nonatomic,strong)NSMutableArray *orderlistArray;//订单列表

@property (weak, nonatomic) IBOutlet UIButton *btn_beginTD;

@property (weak, nonatomic) IBOutlet UIView *view_hiden;


@end

@implementation TDOrderListC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}



- (void)setupUI {
    //添加tableView
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupTableView];
    _btn_beginTD.layer.cornerRadius = 5;
    _btn_beginTD.layer.borderColor = [UIColor colorWithHex:0xbf0021].CGColor;
    _btn_beginTD.layer.borderWidth = 1;
    _btn_beginTD.layer.masksToBounds = YES;
//    self.orderListHeadView = [TDOrderListHeadView orderListHeadView];
//    self.orderListHeadView.frame = CGRectMake(0, 20, 40, 64);
    self.orderListFootView = [TDOrderListHeadView orderListHeadView];
    self.orderListFootView.frame = CGRectMake(0, Height, Width, 0);
//    [self.view addSubview:self.orderListHeadView];
//    UIView *view_bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 20)];
//    view_bg.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:view_bg];
    [self.view addSubview:self.orderListFootView];
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadHistoryData];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
}

- (IBAction)beginTDBtnClick:(UIButton *)sender {
    TDSearchCarController *searchCarC = [[TDSearchCarController alloc] init];
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:searchCarC];
    searchCarC.isPush = YES;
    [self presentViewController:nav animated:YES completion:nil];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    [self loadData];

}


- (void)setupTableView {
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDOrderListCell" bundle:nil] forCellReuseIdentifier:@"TDOrderListCellId"];
    self.tableView.rowHeight = 399;
}


#pragma mark - 实现数据源方法
#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.orderlistArray.count;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    TDOrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TDOrderListCellId" forIndexPath:indexPath];
    TDOrderListModel *enumListModel = self.orderlistArray[indexPath.row];
    cell.listModel = enumListModel;
    //返回
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TDOrderDetailC *orderDetailC = [[TDOrderDetailC alloc] init];
    orderDetailC.orderListModel = self.orderlistArray[indexPath.row];
    [self.navigationController pushViewController:orderDetailC animated:YES];
}




- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    return;
    // MARK: - 这计算逻辑 头疼
    if (scrollView.contentOffset.y < -84) {
        CGFloat offsetY = fabs(scrollView.contentOffset.y) - 84;
        self.orderListHeadView.zl_height = offsetY + 64;
    }else {
        self.orderListHeadView.zl_height = 64;
    }
    NSLog(@"-----%.2f-------------",scrollView.contentOffset.y);
    NSLog(@"😀😀%.2f😀😀",scrollView.contentSize.height);

    if ((Height - 49) + scrollView.contentOffset.y >= scrollView.contentSize.height) {
       CGFloat offsetY = fabs((Height - 49) + scrollView.contentOffset.y) - scrollView.contentSize.height;
        self.orderListFootView.zl_height = offsetY+1;
        self.orderListFootView.zl_y = Height-50-offsetY;
    }else {
        self.orderListFootView.zl_y = Height-49;
        self.orderListFootView.zl_height = 0;
    }

}



// MARK: - 加载数据
- (void)loadData {
    [self loadLocalData];
    [self loadNetData];
}
// MARK: - 本地数据
- (void)loadLocalData {
    
}

// MARK: - 获取网络数据-----
- (void)loadNetData {
//    [self showProgressHUD];
    NSDictionary *dic = @{@"prevrows":@"0",
                          @"showrows":showrows
                          };
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:OrderListM parmeters:dic response:^(NSDictionary *response) {
        if (response) {
            [weakSelf progressHUDHideImmediately];
            //保存数据---进行一系列的操作----------
            NSArray *tmpArray = response[@"data"][@"orderlist"];
            weakSelf.orderlistArray = [NSArray yy_modelArrayWithClass:[TDOrderListModel class] json:tmpArray].mutableCopy;
            
            if (weakSelf.orderlistArray.count == 0) {
                weakSelf.view_hiden.hidden = NO;
            }else {
                weakSelf.view_hiden.hidden = YES;
            }
            
            [weakSelf.tableView reloadData];
            if (weakSelf.orderlistArray.count != 0) {
                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.orderlistArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
            
        }else {
            [weakSelf progressHUDHideImmediately];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:@"获取订单列表失败" isSucceed:NO];
    }];
}

// MARK: - 获取历史数据
- (void)loadHistoryData {
//    [self showProgressHUD];
    TDOrderListModel *listModel = self.orderlistArray.firstObject;
    NSString *prevrows = listModel.rowno;
    NSDictionary *dic = @{@"prevrows":prevrows,
                          @"showrows":showrows
                          };
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:OrderListM parmeters:dic response:^(NSDictionary *response) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf progressHUDHideImmediately];

        if (response) {
            //保存数据---进行一系列的操作----------
            NSArray *tmpArray = response[@"data"][@"orderlist"];
            NSArray *tmpListArray = [NSArray yy_modelArrayWithClass:[TDOrderListModel class] json:tmpArray];
            if (tmpListArray.count == 0) {
                weakSelf.noticeText = @"暂无更多历史订单信息";
                return;
            }
            tmpListArray = [[tmpListArray reverseObjectEnumerator] allObjects];
            for (TDOrderListModel *enumModel in tmpListArray) {
                [weakSelf.orderlistArray insertObject:enumModel atIndex:0];
            }
            [weakSelf.tableView reloadData];
           
        }else {
            [weakSelf progressHUDHideImmediately];
        }
    } netError:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf progressHUDHideImmediately];
    }];
}


- (void)loadNewData {
    NSDictionary *dic = @{@"prevrows":@"0",
                          @"showrows":showrows
                          };
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:OrderListM parmeters:dic response:^(NSDictionary *response) {
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf progressHUDHideImmediately];

        if (response) {
            //保存数据---进行一系列的操作----------
            NSArray *tmpArray = response[@"data"][@"orderlist"];
            NSArray *tmpListArray = [NSArray yy_modelArrayWithClass:[TDOrderListModel class] json:tmpArray].mutableCopy;
            if (tmpListArray.count == 0) {
                weakSelf.noticeText = @"暂无新订单信息";
                return;
            }
            
            TDOrderListModel *newTmpModel = tmpListArray.lastObject;
            TDOrderListModel *oldTmpModel = weakSelf.orderlistArray.lastObject;
            if ([newTmpModel.orderid isEqualToString:oldTmpModel.orderid]) {
                //表示没有新数据插入
                return;
            }
            weakSelf.orderlistArray = tmpListArray.mutableCopy;
            [weakSelf.tableView reloadData];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (weakSelf.orderlistArray.count != 0) {
                    [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.orderlistArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                }
            });
        }else {
            [weakSelf progressHUDHideImmediately];
        }
    } netError:^(NSError *error) {
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf progressHUDHideImmediately];
    }];
    
}

- (IBAction)closeBtnClick:(UIButton *)sender {
    if (self.navigationController.childViewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}




@end
